﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetComm;

namespace KWIS900CLIENT.classes
{
    // client server connection resource
    // http://www.codeproject.com/Articles/118485/C-VB-NET-Multi-user-Communication-Library-TCP
    //<author>Marzpet Vardanyan</autho>
    public class Connection
    {
        public NetComm.Client client;
        public NetComm.Host server;
        String name;
        int port;

        public Connection(String name, String type, int port)
        {
            this.name = name;
            this.port = port;
            if (type == "client")
            {
                client = new NetComm.Client();
            }

            if (type == "server")
            {
                server = new NetComm.Host(this.port);

                //Adding event handling methods, to handle the server messages
                server.onConnection += new NetComm.Host.onConnectionEventHandler(Server_onConnection);
                server.lostConnection += new NetComm.Host.lostConnectionEventHandler(Server_lostConnection);
                server.DataReceived += new NetComm.Host.DataReceivedEventHandler(Server_DataReceived);

            }
        }

        public void sendData(String message)
        {
            client.SendData(ConvertStringToBytes(message));
        }
        public void connect(String host)
        {
            client.Connect(host, this.port, this.name);
        }

        public void startListenening()
        {
            server.StartConnection();
            if (server.Listening)
            {
                Console.Out.WriteLine("listening on port " + this.port);
            }
        }


        // event listeners
        // server
        void Server_onConnection(string id)
        {
            Console.Out.WriteLine(id + " connected!" + Environment.NewLine); //Updates the log textbox when new user joined
        }

        void Server_lostConnection(string id)
        {
            Console.Out.WriteLine(id + " lost!" + Environment.NewLine); //Updates the log textbox when new user joined
        }
        void Server_DataReceived(string id, byte[] Data)
        {
            Console.Out.WriteLine(id + ": " + ConvertBytesToString(Data) + Environment.NewLine); //Updates the log textbox when new user joined
        }

        public void disconnect()
        {
            client.Disconnect();
        }

        // helper functions
        public static string ConvertBytesToString(byte[] bytes)
        {
            return ASCIIEncoding.ASCII.GetString(bytes);
        }

        public static byte[] ConvertStringToBytes(string str)
        {
            return ASCIIEncoding.ASCII.GetBytes(str);
        }
    }
}
